import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Badge, Button, Card, Col, DatePicker, Divider, Form, Input, Modal, Row, Select,} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescriptionList from '@/components/DescriptionList';
import styles from './Flow.less';
import ApplyDetailForm from './sub/ApplyDetailForm';
import MoveFileForm from '../Filecenter/sub/MoveFileForm';

const {Description} = DescriptionList;
const {RangePicker} = DatePicker;

const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const applyType = ['个人文件下载', '公共文件下载', '流转', '外发', '编辑','自定义组文件下载'];

// 0个人文件下载1公共文件2流转3外发4编辑
/* eslint react/no-multi-comp:0 */
@connect(({workspaceModel, loading}) => ({
  workspaceModel,
  loading: loading.models.workspaceModel,
}))
@Form.create()
class Flow extends PureComponent {
  state = {
    modalVisible: false,//详情modal
    selectedRows: [],
    formValues: {},
    detail: {},
    endValue: null,
    startValue: null,
    endOpen: false,
    waterOptions:[],
    authOptions: [],
  };

  columns = [
    {
      title: '文件名称',
      dataIndex: 'fileNames',
      width:"30%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    // {
    //   title: '文件大小',
    //   dataIndex: 'fileSize',
    // },
    {
      title: '审核人',
      dataIndex: 'auditUserName',
    },
    {
      title: '申请来源',
      render(val) {
        return applyType[val.applyType];
      },
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '状态',
      dataIndex: 'applyState',
      render(val) {
        // const statusMap = ['default', 'processing', 'success', 'error'];
        // const status = ['关闭', '运行中', '已上线', '异常'];
        // 0申请中1通过2拒绝
        let text = "--";
        let status = "";
        if (val == 0) {
          status = "processing";
          text = "申请中";
        } else if (val == 1) {
          status = "success";
          text = "通过";
        } else if (val == 2) {
          status = "error";
          text = "拒绝";
        }
        return <Badge status={status} text={text}/>;
      },
    },
    {
      title: '操作',
      render: (text, record) => {
        const applyType = record.applyType;
        const applyState = record.applyState;
        let detail = <a onClick={() => this.handleModalVisible(true, record)}>详情</a>;
        let remove = <a onClick={() => this.deleteData(text.id)}>删除</a>;
        /* let download = <Popconfirm title="是否要下载此文件？" onConfirm={() => this.preDownloadItem(record)}>
           <a>下载</a>
         </Popconfirm>;*/
        let download = <a onClick={() => this.isDownload(record)}>下载</a>;
        let move = <a onClick={() => this.handleMoveModalVisible(true, record)}>移动</a>;
        let edit = <a onClick={() => this.quickEdit(record)}>编辑</a>;

        if (applyState == 0) {
          //未审核的只能看
          return (
            <Fragment>
              {detail}
            </Fragment>
          )

        } else if (applyState == 2) {
          //被拒绝的只能看、删除
          return (
            <Fragment>
              {detail}
              <Divider type="vertical"/>

              {remove}
            </Fragment>
          )
        } else if (applyState == 1) {
          //审核通过的分情况，
          //  0个人文件下载1公共文件2流转3外发4编辑5自定义组
          if (applyType == 0||applyType == 5) {
            return (<Fragment>
                {detail}
                <Divider type="vertical"/>
                {download}
                <Divider type="vertical"/>
                {remove}
              </Fragment>
            )
            }else if (applyType == 1) {
            return (<Fragment>
              {detail}
              <Divider type="vertical"/>
              {download}
              <Divider type="vertical"/>
              {remove}
            </Fragment>)

          } else if (applyType == 2) {
            return (<Fragment>
              {detail}
              <Divider type="vertical"/>
              {remove}
            </Fragment>)

          } else if (applyType == 3) {
            return (<Fragment>
              {detail}
              <Divider type="vertical"/>
              {download}
              <Divider type="vertical"/>
              {remove}
            </Fragment>)

          } else if (applyType == 4) {
            return (<Fragment>
              {detail}
              <Divider type="vertical"/>
              {edit}
              <Divider type="vertical"/>
              {remove}
            </Fragment>)
          }
        }
      },
    },
  ];

  queryOutWaterOptions = () => {
    const {dispatch} = this.props;
    let params = {dataDictTypeCode: 'out_water_control', status: 0};
    dispatch({
      type: 'workspaceModel/queryDataDict',
      payload: params,
      callback: (res) => {
        if (res.result == "ok" && res.data) {
          let waterOptions = [];
          res.data.dataList.forEach(item => {
            waterOptions.push({label: item.dataDictName, value: item.dataDictValue});
          })
          this.setWaterOptions(waterOptions);

        }
      },
    });
  };
  setWaterOptions = (options) => {
    this.setState({waterOptions: options});
  }

  /**
   * 查询外发的权限
   */
  queryOutRightControl = () => {
    const {dispatch} = this.props;
    let params = {dataDictTypeCode: 'out_right_control', status: 0};
    dispatch({
      type: 'workspaceModel/queryDataDict',
      payload: params,
      callback: (res) => {
        if (res.result == "ok" && res.data) {
          let authOptions = [];
          res.data.dataList.forEach(item => {
            authOptions.push({label: item.dataDictName, value: item.dataDictValue});
          })

          this.setAuthOptions(authOptions);
        }
      },
    });
  };
  setAuthOptions = (options) => {
    this.setState({authOptions: options});
  }


  /***编辑文件**/
  quickEdit = record => {
    //获取编辑地址
    const {dispatch} = this.props;
    dispatch({
      type: 'workspaceModel/getEditLinkPath',
      payload: {
        fileId: record.fileIds,
      },
      callback: (res) => {
        if (res.result == "ok") {
          // message.success(res.msg);
          let path = res.data;
          if (path) {
            window.open(path, "_self");
          } else {
            Modal.error({title: '操作失败', content: "缺少路径，无法预览"});
          }
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });

  };

  isDownload = record => {
    Modal.confirm({
      title: '下载',
      content: '您确定要下载吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.preDownloadItem(record),
    });
  }
  preDownloadItem = record => {
    const {dispatch} = this.props;
    dispatch({
      type: 'workspaceModel/downloadApplyFiles',
      payload: {
        applyId: record.id,
      },
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  };

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  // 删除方法
  handleDeleteData(id) {
    const {dispatch} = this.props;
    dispatch({
      type: 'workspaceModel/fileapplyDelete',
      payload: {id},
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.queryApplyPageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  componentDidMount() {
    this.queryApplyPageList();
    this.queryOutWaterOptions();
    this.queryOutRightControl();
  }

  /**
   * 移动文件弹出框
   * @param flag
   * @param record
   */
  handleMoveModalVisible = (flag, record) => {
    if (flag) {
      this.queryDirTreeList(record.applyUserCode);
    }

    this.setState({
      moveModalVisible: !!flag,
      record: record || {},
    });
  };

  handleMove = (id, record) => {
    const {dispatch} = this.props;
    const params = {
      applyId: record.id,
      targetFileDirId: id,
    }
    dispatch({
      type: 'workspaceModel/moveFile',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.handleMoveModalVisible();
          this.queryApplyPageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  queryDirTreeList(userCode) {
    const {dispatch} = this.props;
    dispatch({
      type: 'workspaceModel/queryDirTreeList',
      payload: {userCode},
    });
  }


  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {formValues} = this.state;

    this.queryApplyPageList(formValues, pagination.pageSize, pagination.current - 1)
  };

  queryApplyPageList(data, pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      fileNames: data && data.fileNames || '',
      applyState: data && data.applyState,
      applyType: data && data.applyType,
      startTime: data && data.startTime && moment(data.startTime).format('YYYY-MM-DD'),
      endTime: data && data.endTime && moment(data.endTime).format('YYYY-MM-DD'),
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'workspaceModel/fileapplyList',
      payload: values,
    });
  }

  previewItem = record => {
    const params = {
      fileId: record.fileIds,
    }
    this.previewFile(params)
  };

  previewFile(params) {
    const {dispatch} = this.props;
    dispatch({
      type: 'workspaceModel/fileapplyPreivew',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          let path = res.data;
          if (path) {
            window.open(path, "_self");
          } else {
            Modal.error({title: '操作失败', content: "缺少路径，无法预览"});
          }
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      this.queryApplyPageList(values);
    });
  };

  disabledStartDate = startTime => {
    const {endTime} = this.state;
    if (!startTime || !endTime) {
      return false;
    }
    return startTime.valueOf() > endTime.valueOf();
  };

  disabledEndDate = endTime => {
    const {startTime} = this.state;
    if (!endTime || !startTime) {
      return false;
    }
    return endTime.valueOf() <= startTime.valueOf();
  };

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  };

  onStartChange = value => {
    this.onChange('startTime', value);
  };

  onEndChange = value => {
    this.onChange('endTime', value);
  };

  handleStartOpenChange = open => {
    if (!open) {
      this.setState({endOpen: true});
    }
  };

  handleEndOpenChange = open => {
    this.setState({endOpen: open});
  };


  renderSimpleForm() {
    const {
      form: {getFieldDecorator, getFieldValue},
    } = this.props;
    const { startTime, endTime, endOpen } = this.state;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="文件名称">
              {getFieldDecorator('fileNames')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="状态">
              {/*0申请中1通过2拒绝*/}
              {getFieldDecorator('applyState')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="">--请选择--</Option>
                  <Option value={0}>申请中</Option>
                  <Option value={1}>通过</Option>
                  <Option value={2}>拒绝</Option>
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="申请来源">
              {/*0个人文件下载1公共文件2流转3外发4编辑*/}
              {getFieldDecorator('applyType')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="">--请选择--</Option>
                  <Option value={2}>流转</Option>
                  <Option value={3}>外发</Option>
                  <Option value={4}>编辑</Option>
                  <Option value={0}>个人文件下载</Option>
                  <Option value={1}>公共文件下载</Option>
                  <Option value={5}>自定义组文件下载</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={16} sm={24}>
            <FormItem key="startTime" {...this.formLayout} label="申请时间">
              {getFieldDecorator('startTime', {
                rules: [{required: false, message: '请选择开始时间！'}],
                initialValue: startTime,
              })(
                <DatePicker
                  disabledDate={this.disabledStartDate}
                  format="YYYY-MM-DD"
                  placeholder="选择开始时间"
                  onChange={this.onStartChange}
                  onOpenChange={this.handleStartOpenChange}
                />
              )}
              <span> -- </span>
              {getFieldDecorator('endTime', {
                  rules: [{required: false, message: '请选择结束时间！'}],
                  initialValue: endTime,
                })(
                  <DatePicker
                    disabledDate={this.disabledEndDate}
                    format="YYYY-MM-DD"
                    placeholder="请选择结束时间"
                    onChange={this.onEndChange}
                    open={endOpen}
                    onOpenChange={this.handleEndOpenChange}
                  />
                )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }


  handleModalVisible = (flag, record) => {
    this.setState({
      modalVisible: !!flag,
      detail: null,
    });

    if (flag && record) {
      this.queryApplyDetail(record.id);
    }
  };
  //进行审核
  handleApplyAudit = () => {

  };

  //查询申请详情
  queryApplyDetail = id => {
    const {dispatch} = this.props;
    let queryForm = {id: id};
    dispatch({
      type: 'workspaceModel/queryApplyDetail',
      payload: queryForm,
    });
  };


  render() {
    const {
      workspaceModel: {data, detail, dirTreeList},
      loading,
    } = this.props;
    const {selectedRows, modalVisible, moveModalVisible, record,waterOptions,authOptions,} = this.state;
    //上传文件
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      handleApplyAudit: this.handleApplyAudit,
    };

    //移动文件
    const moveMethods = {
      handleMove: this.handleMove,
      handleModalVisible: this.handleMoveModalVisible,
    };


    return (
      <PageHeaderWrapper title="我的申请">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <TableList
              className={styles.tdPadding}
              hideRowSelection={true}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
          <MoveFileForm {...moveMethods}
                        modalVisible={moveModalVisible}
                        record={record}
                        dirTreeList={dirTreeList}
          />
          {detail && modalVisible ? (
            <ApplyDetailForm waterOptions={waterOptions} authOptions={authOptions} {...parentMethods} record={detail} modalVisible={modalVisible}/>
          ) : null}

        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Flow;
